package com.security.demo.realm;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.security.demo.service.UserService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    UserService userService;

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        com.security.demo.model.User user = userService.findByUsername(username);
        if (user == null) {
            if (log.isDebugEnabled()) log.debug("{} not found username ", username);
            throw new UsernameNotFoundException("not found username " + username);
        }
        Set<String> pers = userService.findPermissions(username);
        User userdetail = new User(username, user.getPassword(), true, true, true, user.getLocked(),
                getGrantedAuthorities(pers));
        return userdetail;
    }

    private Collection<GrantedAuthority> getGrantedAuthorities(Set<String> pers) {
        Collection<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
        for (String per : pers) {
            SimpleGrantedAuthority simpleAuth = new SimpleGrantedAuthority(per);
            authorities.add(simpleAuth);
        }
        if (log.isDebugEnabled()) log.debug("username has permission {} ", pers);
        return authorities;
    }

}
